#ifndef     __BYTES_H
#define     __BYTES_H

#include <stdint.h>
#include <string.h>
#include "./encode.h"
#include "./decode.h"

namespace utils {

struct byte_view_t {

    inline byte_view_t(const uint8_t *b, uint32_t l) : buf(b), len(l) {}

    inline byte_view_t() : buf(nullptr), len(0) {}

    inline uint32_t encode(uint8_t *b) const {
        encode_uint16(b, len);
        memcpy(b + 2, buf, len);
        return len + 2;
    }

    static uint32_t decode(const uint8_t *b, uint32_t size, byte_view_t& val) {
        if (size < 2) {
            return DecodeFail;
        }
        uint16_t len = decode_uint16(b);
        if (size < (2 + len)) {
            return DecodeFail;
        }
        val.len = len;
        val.buf = b + 2;
        return len + 2;
    }

    const uint8_t *buf;
    uint32_t len;

};

}

#endif
